package com.StarStudio.Controller;

import com.StarStudio.Domain.Device;
import com.StarStudio.Domain.HttpStatusCode;
import com.StarStudio.Domain.MessageConstant;
import com.StarStudio.Domain.Result;
import com.StarStudio.Service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/devices")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    @GetMapping
    public Result getAll(){
        List<Device> deviceList = null;
        try {
            deviceList = deviceService.getAll();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR, MessageConstant.DEVICE_QUERY_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS, MessageConstant.DEVICE_QUERY_SUCCESS, deviceList);
    }

    @GetMapping("/{deviceId}")
    public Result getById(@PathVariable int deviceId){
        Device deviceById = null;
        try {
            deviceById = deviceService.getById(deviceId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR, MessageConstant.DEVICE_QUERY_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS, MessageConstant.DEVICE_QUERY_SUCCESS, deviceById);
    }

    @PostMapping("/{zoneId}")
    public Result add(@RequestBody Device device, @PathVariable int zoneId) {
        try {
            deviceService.add(device,zoneId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR, MessageConstant.DEVICE_ADD_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS, MessageConstant.DEVICE_ADD_SUCCESS);
    }

    @PutMapping
    public Result update(@RequestBody Device device){
        try {
            deviceService.update(device);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR, MessageConstant.DEVICE_UPDATE_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS, MessageConstant.DEVICE_UPDATE_SUCCESS);
    }

    @DeleteMapping("/{deviceId}")
    public Result delete(@PathVariable Integer deviceId){
        try {
            deviceService.delete(deviceId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR, MessageConstant.DEVICE_DELETE_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS, MessageConstant.DEVICE_DELETE_SUCCESS);
    }

}